const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取所有用户地址
router.post('/', (req, res) => {
    const sql = 'select * from address';
    db.query(sql, [], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                err: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});

// 添加用户地址
router.post('/insert', (req, res) => {
    const sql = 'INSERT INTO address (username, phone, address, time) VALUES (?, ?, ?, ?)';
    const { username, phone, address, time } = req.body;
    db.query(sql, [username, phone, address, time], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                error: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});

// 删除用户地址
router.post('/delete', (req, res) => {
    const sql = 'DELETE FROM address where id=?';
    db.query(sql, [req.body.id], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                err: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});

// 修改用户地址
router.post('/update', (req, res) => {
    const sql = 'UPDATE address SET username=?, phone=?, address=?, time=? WHERE id=?';
    const { username, phone, address, time, id } = req.body;
    db.query(sql, [username, phone, address, time, id], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                err: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});

module.exports = router;